<?php
/**
 * 余额记录
 */

namespace app\api\model;
use think\Model;

class BalanceRecord extends Model
{
    /**
    * 创建余额记录
    */
    public function _create($data){
        return $this->save($data);
    }
    
    
    /**
    * 列表
    */
    public function _list($where, $order_by="created asc", $page_size = PAGE_SIZE_API){
        $obj = $this->order($order_by);
        $data = $this->where($where)
            ->field('id, type_id, image, remark, money, created')
            ->order($order_by)
            ->paginate($page_size)
            ->toArray();
        return $data;
    }
    
    
    /**
    * 收徒明细
    * @param mid int 会员id
    * @param order_by string 排序规则
    * @param page_size int 分页大小
    * @return array
    */
    public function _apprenticeIncomeList($mid, $order_by="created asc", $page_size = PAGE_SIZE_API){
        $obj = $this->order($order_by);
        $data = $this->alias('br')
            ->field('br.id, br.type_id,  br.remark, br.money, br.created, m.unique')
            ->join("member m", "m.id = br.child_id")
            ->order($order_by)
            ->where([['br.mid', '=', $mid]])
            ->paginate($page_size)
            ->toArray();
        return $data;
    }
    
    /**
    * 今日余额
    * @param mid 会员id
    * @param udid 设备udid
    * @param isMember 是否是会员
    * @return float 余额
    */
    public function _todayBalance($mid, $udid, $isMember){
        $balance = 0;
        
        $start = strtotime(date("Y-m-d"));
        $end = strtotime(date("Y-m-d")) + 24 * 3600;
        if($isMember){
            $where = [
                ['mid', '=', $mid],
                ['created', '>=', $start],
                ['created', '<', $end],
            ];
            $balance = $this->where($where)->sum('money');
        }else{
            $where = [
                ['mid', '=', 0],
                ['udid', '=', $udid],
                ['is_tourist', '=', 1],
                ['created', '>=', $start],
                ['created', '<', $end],
            ];
            $balance = $this->where($where)->sum('money');
        }
        
        return $balance;
    }
}